//
//  CycleScrollView.m
//  轮播scrollerView
//
//  Created by CheMiMacPro on 15/4/20.
//  Copyright (c) 2015年 CheMiMacPro. All rights reserved.
//

#import "CycleScrollView.h"
#import "TAPageControl.h"
#import "CycleCollectionViewCell.h"

@interface CycleScrollView()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate>
{
    UICollectionView             *_mainView;
    UICollectionViewFlowLayout   *_flowLayout;
    NSTimer                      *_timer;
    NSInteger                     _totalItemCount;
    TAPageControl                *_pageControl;
}
@end


@implementation CycleScrollView

#pragma mark - System Modules

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        _pageControlAliment = PageContolAlimentCenter;
        _scrollTimeInterval = 3.0;
        [self setupMainView];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    _mainView.frame = self.bounds;
    if (_mainView.contentOffset.x == 0) {
        [_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_totalItemCount * 0.5 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    
    CGSize size = [_pageControl sizeForNumberOfPages:self.imagesGroup.count];
    CGFloat x = (self.frame.size.width - size.width) * 0.5;
    if (self.pageControlAliment == PageContolAlimentRight) {
        x = _mainView.frame.size.width - size.width - 10;
    }
    CGFloat y = _mainView.frame.size.height - size.height - 10;
    _pageControl.frame = CGRectMake(x, y, size.width, size.height);
    [_pageControl sizeToFit];
}

#pragma mark - Private Modules

- (void)setupMainView
{
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.itemSize = self.frame.size;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _mainView = [[UICollectionView alloc] initWithFrame:self.frame collectionViewLayout:_flowLayout];
    _mainView.backgroundColor = [UIColor lightGrayColor];
    _mainView.pagingEnabled = YES;
    _mainView.showsHorizontalScrollIndicator = NO;
    _mainView.showsVerticalScrollIndicator = NO;
    [_mainView registerClass:[CycleCollectionViewCell class] forCellWithReuseIdentifier:@"ID"];
    _mainView.delegate = self;
    _mainView.dataSource = self;
    [self addSubview:_mainView];
}

- (void)setupTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:_scrollTimeInterval target:self selector:@selector(automaticScroll) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)automaticScroll
{
    int currentIndex = _mainView.contentOffset.x / _flowLayout.itemSize.width;
    int targetIndex = currentIndex + 1;
    if (targetIndex == _totalItemCount) {
        targetIndex = _totalItemCount * 0.5;
        [_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    [_mainView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}

- (void)setupPageControl
{
    _pageControl = [[TAPageControl alloc] init];
    _pageControl.numberOfPages = self.imagesGroup.count;
    [self addSubview:_pageControl];
}


#pragma mark - Public Modules

+ (instancetype)cycleScrollViewWithFrame:(CGRect)frame imagesGroup:(NSArray *)imagesGroup
{
    CycleScrollView *cycleScrollView = [[self alloc] initWithFrame:frame];
    cycleScrollView.imagesGroup = imagesGroup;
    return cycleScrollView;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    _flowLayout.itemSize = self.frame.size;
}

- (void)setImagesGroup:(NSArray *)imagesGroup
{
    _imagesGroup = imagesGroup;
    _totalItemCount = imagesGroup.count * 100;
    [self setupTimer];
    [self setupPageControl];
}

- (void)setScrollTimeInterval:(CGFloat)scrollTimeInterval
{
    _scrollTimeInterval = scrollTimeInterval;
    [_timer invalidate];
    _timer = nil;
    [self setupTimer];
}


#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _totalItemCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CycleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ID" forIndexPath:indexPath];
    long itemIndex = indexPath.item % self.imagesGroup.count;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:self.imagesGroup[itemIndex]] placeholderImage:[UIImage imageNamed:@"imgbg_home_banner"]];
    if (_titlesGroup.count) {
        cell.title = _titlesGroup[itemIndex];
    }
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_delegate respondsToSelector:@selector(cycleScrollView:didSelectItemAtIndex:)]) {
        [_delegate cycleScrollView:self didSelectItemAtIndex:indexPath.item % self.imagesGroup.count];
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int itemIndex = (scrollView.contentOffset.x + _mainView.frame.size.width * 0.5) / _mainView.frame.size.width;
    int indexOnPageControl = itemIndex % self.imagesGroup.count;
    _pageControl.currentPage = indexOnPageControl;

}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_timer invalidate];
    _timer = nil;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self setupTimer];
}




@end
